package com.baseweb.webadmin.weixin.pay;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.baseweb.webadmin.weixin.utils.Constant;

/***
 * 微信oauth认证
 * 用户授权
 * @author wcc
 *
 */
@WebServlet(urlPatterns={"/test/userOauth"})
public class WeixinOAuth  extends HttpServlet {
	private   static  Logger logeer = LoggerFactory.getLogger(WeixinOAuth.class);

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		logeer.info("user   accsee  doPost");
		userOauth(req, resp);
	}
	
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
    
	
	
	/***
	 * 用户同意授权，获得code
	 * 授权后回回调Constant.REDIRECT_URI配置的函数
	 * @return code
	 */
	public void userOauth(HttpServletRequest req, HttpServletResponse resp) {
		logeer.info("开始微信认证");
		logeer.info("开始微信认证---->  sessionId--->:"+req.getSession().getId());
		 try {
			StringBuffer getCodeUrl = new StringBuffer("https://open.weixin.qq.com/connect/oauth2/authorize");
			getCodeUrl.append("?appid=").append(Constant.WX_APPID).append("&redirect_uri=").append(URLEncoder.encode(Constant.REDIRECT_URI,"utf-8"))
					.append("&response_type=code&scope=snsapi_userinfo&showwxpaytitle=1&state=").append(Constant.STATE)
					.append("#wechat_redirect");
			logeer.info("开始微信认证  url:"+getCodeUrl.toString());
		    logeer.info("http  Redirect:地址被转发了");
		 //重定向请求就可
		 resp.sendRedirect(getCodeUrl.toString());
		} catch (IOException e) {
			logeer.error("在请求微信oauth认证时出现异常：",e);
		}
		
	}
}
